package com.goktech.commons.utils;

import java.util.Map;

public class TagUtils {

	private final static String DEFAULTSUFFIX = "}";
	
	private final static String DEFAULTPREFIX = "${";
	
	public static String getKey(String content){
		int start = content.indexOf(DEFAULTPREFIX)+DEFAULTPREFIX.length();
		int end = content.indexOf(DEFAULTSUFFIX);
		if(start == -1 || end == -1){
			return null;
		}
		return  content.substring(start, end);
	}
	
	public static int[] getPoint(String content) {
		int start = content.indexOf(DEFAULTPREFIX);
		int end = content.indexOf(DEFAULTSUFFIX);
		int[] result = new int[2];
		result[0] = start;
		result[1] = end;
		return result;
	}
	
	private static String sub(int start,int end,String content) {
		if(content != null && content.equals("")) {
			return content;
		}
		return content.substring(start,end);
	}
	public static String replace(String content,Map<String,Object> data) {
		int[] result = null;
		do {
			result = getPoint(content);
			if(result[1] != -1 && result[0] != -1) {
				content = content.substring(0, result[0]) + 
						data.get(sub(result[0]+DEFAULTPREFIX.length(),result[1],content))+
								content.substring(result[1]+1,content.length());
			}
		}while(result[1] != -1 && result[0] != -1);
		return content;
	}
	
	/**
	 * 将自定义的字符串转换为数字
	 * @param number
	 * @return
	 */
	public static int getInteger(String number,Map<String,Object> data){
		String key = getKey(number);
		if(StringUtils.isEmpty(key)){
			return Integer.parseInt(number);
		}else{
			Object value = data.get(key);
			if(value == null){
				return 0;
			}
			if(value instanceof String){
				return Integer.parseInt((String)value);
			}
			if(value instanceof Integer){
				return (Integer)value;
			}
			return 0;
		}
	}
	
	public static float getFloat(String number,Map<String,Object> data){
		String key = getKey(number);
		if(StringUtils.isEmpty(key)){
			return Integer.parseInt(number);
		}else{
			Object value = data.get(key);
			if(value == null){
				return 0;
			}
			if(value instanceof String){
				return Float.parseFloat((String)value);
			}
			if(value instanceof Float){
				return (Float)value;
			}
			return 0;
		}
	}
}
